<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\api\controller\user;

use app\api\controller\Controller;
use app\api\model\Order as OrderModel;
use app\common\model\Position as PositionModel;
use app\common\model\User as UserModel;
use app\common\model\DeliveryImg as DeliveryImgModel;
use app\store\model\UploadFile;
use app\common\library\storage\Driver as StorageDriver;
use app\store\model\Setting as SettingModel;
use app\common\model\Myfav as MyfavModel;

/**
 * Description of Delivery
 *  服务员接口
 * @author Administrator
 */
class Bartender extends Controller
{
    /* @var \app\api\model\User $user */

    private $user;
    private $config;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();
        // 存储配置信息
        $this->config = SettingModel::getItem('storage');
    }

    /**
     * 记录定位信息
     * @param type $longitude
     * @param type $latitude
     */
    public function addmap($longitude, $latitude, $status, $order_id)
    {

        $lngLat = $latitude . ',' . $longitude;
        $aData = [
            'key' => 'P5OBZ-VK43J-PUOFS-FAKLJ-CTJME-OVB3Y', //密匙
            'location' => $lngLat, //经纬度信息
        ];
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/'; //获取详细地址信息

        $aMap = postCurl($url, $aData);
        $aArrMap = json_decode($aMap, true); //转化为数组
        if ($aArrMap['status']) {
            return $this->renderError($aArrMap['message']);
        }
        $maOrder = [
            'longitude' => $longitude, //纬度
            'latitude' => $latitude, //经度
            'user_id' => $this->user['user_id'], //服务员id
            'status' => $status, //服务员状态
            'create_time' => time(), //记录时间
            'add_text' => $aArrMap['result']['address'], //具体地址（从腾讯API接口获取）
            'order_id' => $order_id, //订单id
            'wxapp_id' => $this->user['wxapp_id'], //服务员id
        ];
        //根据服务员状态写入记录表
        switch ($status) {
            case 1:
                //写入轨迹表
                $aSave = (new PositionModel)->allowField(true)->save($maOrder);
                break;
            case 2:
                $where = ['wxapp_id' => $this->user['wxapp_id'], 'status' => 2, 'user_id' => $this->user['user_id']];
                $aIf = [];
                //更新用户表
                $aIf = (new PositionModel)->allowField(true)->get($where);
                if ($aIf) {
                    $aSave = (new PositionModel)->allowField(true)->save($maOrder, $where);
                } else {
                    $aSave = (new PositionModel)->allowField(true)->save($maOrder);
                }
                break;
            case 3:
                break;
            default:
                break;
        }
        return $this->renderSuccess(compact('userInfo', 'orderCount'));
    }

    /**
     * 获取服务员列表
     * @param type $limit 分页显示条数
     * @param type $page 第几页
     * @return type
     */
    public function getdelivery($limit, $page, $user_type, $search, $longitude, $latitude)
    {

        $lngLat = $latitude . ',' . $longitude;
        $aWhere = [];
        if ($limit < 1) {
            $limit = 10;
        }
        if ($page < 1) {
            $limit = 1;
        }
        if ($user_type) {
            $aWhere['a.user_type'] = $user_type;
        }
        if ($search) {
            $aWhere['a.nickName'] = ['like', '%' . $search . '%']; //搜索
        }
        #--这两个变量未传入，待定：
        $isdefault = 'Y';
        $orderid = 1;   #--运动轨迹表与订单相关联：

        $list = (new UserModel)->alias('a')
            ->join('position v', 'a.user_id = v.user_id', 'left')//运动轨迹表
            ->join('myfav m', 'a.user_id = m.p_id', 'left')//收藏表
            ->join('delivery_img g', 'a.user_id = g.user_id && g.is_delete=0 && g.idx=0', 'left')//照片表
            ->join('bartender b', 'a.user_id = b.user_id ', 'left')//服务员等级
            ->where($aWhere)
            ->order('a.isonline,a.isworking,m.index')
            ->group('a.user_id')
            ->field('MAX(v.p_id),g.*,m.*,v.*,a.*,b.*')
            ->paginate($limit, false, ['page' => $page]);

        #--测试用：
        /*if ($this->user['user_id'] == 25) {
            $list = (new UserModel)->alias('a')->fetchSql(true)
            ->join('position v', 'a.user_id = v.user_id', 'left')//运动轨迹表
            ->join('myfav m', 'a.user_id = m.p_id', 'left')//收藏表
            ->join('delivery_img g', 'a.user_id = g.user_id && g.is_delete=0', 'left')//照片表
            ->join('bartender b', 'a.user_id = b.user_id ', 'left')//服务员等级
            ->where($aWhere)
                ->order('a.isonline,a.isworking,m.index')
                ->group('a.user_id')
                ->field('MAX(v.p_id),g.*,m.*,v.*,a.*,b.*')
                ->paginate($limit, false, ['page' => $page]);halt($list);
        }*/

        if (count($list) == 0) {
            $list = [];
        } else {

            //计算距离
            $url = 'https://apis.map.qq.com/ws/distance/v1/?parameters';
            $aDatas = [
                'mode' => 'driving', //行进方式 driving（驾车）、walking（步行）
                'key' => 'P5OBZ-VK43J-PUOFS-FAKLJ-CTJME-OVB3Y', //密匙
                'to' => $lngLat, //终点经纬度
            ];
            $from = '';

            $age = date("y", time());

            #查询结果再处理：
            foreach ($list as $key => $value) {
                $list[$key]['b_id'] = $value['user_id'];
                $list[$key]['age'] = $age - $value['year'];
                $list[$key]['user_img'] = ($value['file_url']) ? $value['file_url'] . '/' . $value['file_name'] : $value['avatarUrl'];
                //调接口
                $from .= $value['latitude'] . ',' . $value['longitude'] . ';';
            }
            $aDatas['from'] = trim($from, ';');
            //请求接口
            $aMap = curl($url, $aDatas);
            //计算距离和时间
            $aMap = json_decode($aMap, true);
            if (!empty($aMap['result']['elements'])) {
                $aApi = $aMap['result']['elements'];
                foreach ($list as $key => $value) {
                    foreach ($aApi as $k => $v) {
                        if ($value['latitude'] == $v['from']['lat'] && $value['longitude'] == $v['from']['lng']) {
                            $list[$key]['space'] = $v['distance'];
                            $list[$key]['time'] = $v['duration'];
                        }
                    }
                }
            }
        }

        return $this->renderSuccess($list);

    }

    /**
     * 根据b_id获取服务员信息
     * @return type
     */
    public function getDeliveryByID()
    {
        $aGet = $this->request->get();
        $aWhere = ['a.user_id' => $aGet['b_id'], 'user_type' => 3];
        $list = (new UserModel)->alias('a')
            ->join('bartender b', 'a.user_id = b.user_id ', 'left')//服务员等级
            ->where($aWhere)
            ->field('a.*,b.*')
            ->select();
        if ($list) {
            return $this->renderSuccess($list, '获取服务员信息成功');
        }
        return $this->renderError('该服务员不存在');
    }

    /**
     * 收藏服务员列表
     * @param type $limit 分页显示条数
     * @param type $page 第几页
     * @return type
     */
    public function getmyfav($limit, $page, $search)
    {

        $aWhere = [];
        if ($limit < 1) {
            $limit = 10;
        }
        if ($page < 1) {
            $page = 1;
        }
        if ($search) {
            $aWhere['m.nickName'] = ['like', '%' . $search . '%']; //搜索
        }
        $aWhere['a.user_id'] = $this->user['user_id']; //登陆用户id
        $list = (new MyfavModel)->alias('a')
            ->join('user m', 'm.user_id = a.p_id', 'left')//用户表
            ->join('delivery_img g', 'a.p_id = g.user_id', 'left')//服务员上传照片表
            ->join('bartender b', 'a.p_id = b.user_id ', 'left')//服务员等级
            ->where($aWhere)
            ->order('a.index desc')
            ->group('a.p_id')
            ->paginate($limit, false, ['page' => $page]);

        return $this->renderSuccess($list);

    }

    /**
     * 收藏服务员
     * @b_id 要收藏服务员的id
     * @param type $limit 分页显示条数
     * @param type $page 第几页
     * @return type
     */
    public function addmyfav()
    {

        #--获取前端参数：
        $aPost = $this->request->post();

        #-- 拦截：
        if (!(new UserModel)->get(['user_id' => $aPost['b_id'], 'user_type' => 3, 'status' => 3])) {
            return $this->renderError('该服务员不存在或已被禁用');
        }
        if ((new MyfavModel)->get(['user_id' => $this->user['user_id'], 'p_id' => $aPost['b_id']])) {
            return $this->renderError('该服务员已收藏');
        }

        #--排序：
        if (empty($aPost['index'])) {
            $indexs = (new MyfavModel)->where(['user_id' => $this->user['user_id']])->order('index DESC')->limit(1)->find();
            $aPost['index'] = (empty($indexs)) ? 1 : $indexs['index'] + 1;
        }

        #--组装保存数据：
        $pUser = [
            'user_id' => $this->user['user_id'],
            'p_id' => $aPost['b_id'],
            'index' => $aPost['index'],
            'create_time' => time(),
            'wxapp_id' => $this->wxapp_id,
        ];

        $aReturn = (new MyfavModel)->allowField(true)->save($pUser, false);
        if ($aReturn) {
            return $this->renderSuccess($aPost, '收藏成功');
        }

    }

    /**
     * 取消收藏服务员
     * @b_id 要取消收藏服务员的id
     * @param type $limit 分页显示条数
     * @param type $page 第几页
     * @return type
     */
    public function delmyfav()
    {

        #--获取前端参数：
        $aPost = $this->request->post();

        #-- 拦截：
        if (!(new MyfavModel)->get(['user_id' => $this->user['user_id'], 'p_id' => $aPost['b_id']])) {
            return $this->renderError('该服务员已取消收藏');
        }

        $aReturn = (new MyfavModel)->where(['p_id' => $aPost['b_id']])->delete();
        if ($aReturn) {
            return $this->renderSuccess($aPost, '取消收藏成功');
        }

    }

    /**
     * 服务员图片列表
     * @param type $limit 分页显示条数
     * @param type $page 第几页
     * @return type
     */
    public function getimglist($limit, $page, $b_id)
    {
        $aWhere = [];
        if ($limit < 1) {
            $limit = 10;
        }
        if ($page < 1) {
            $limit = 1;
        }
        $aWhere['a.user_id'] = $b_id;
        $aWhere['a.is_delete'] = 0;
        $list = (new DeliveryImgModel)->alias('a')
//            ->join('myfav m', 'a.user_id = m.p_id', 'left')  //收藏表
//            ->join('delivery_img g', 'a.user_id = g.user_id', 'left')  //收藏表
            ->where($aWhere)
            ->order(['idx'])
//            ->group('a.user_id')
//                ->field('o.user_name,y.quantity as quantity_use ,v.*,v.docdate as docdates,f.pay_name,f.pay_type,a.*,s.shop_name as name,t.btext as name,p.user_name as audit_name')//,
            ->paginate($limit, false, ['page' => $page]);
        $aData = [];
        if ($list) {
            $aData = $list->toArray();
        }
        return $this->renderSuccess($list);
    }

    /**
     * 删除服务员图片
     * @param type $fileIds
     * @return type
     */
    public function deletefiles($fileIds)
    {
        $model = new DeliveryImgModel;
        $model->allowField(true)->save(['is_delete' => 1], ['d_id' => ['in', $fileIds]]);
        return json(['code' => 1, 'msg' => '删除成功', 'data' => $fileIds]);
    }

    /**
     * 图片上传接口
     * @param int $group_id
     * @return array
     * @throws \think\Exception
     */
    public function uploadimg($group_id = -1, $isdefault)
    {
        // 实例化存储驱动
        $StorageDriver = new StorageDriver($this->config);
        // 上传图片
        if (!$StorageDriver->upload())
            return json(['code' => 0, 'msg' => '图片上传失败' . $StorageDriver->getError()]);
        // 图片上传路径
        $fileName = $StorageDriver->getFileName();
        // 图片信息
        $fileInfo = $StorageDriver->getFileInfo();
        // 添加文件库记录
        $uploadFile = $this->addUploadFile($group_id, $fileName, $fileInfo, 'image', $isdefault);
        // 图片上传成功
        return json(['code' => 1, 'msg' => '图片上传成功', 'data' => $uploadFile]);
    }

    /**
     * 添加文件库上传记录
     * @param $group_id
     * @param $fileName
     * @param $fileInfo
     * @param $fileType
     * @return UploadFile
     */
    public function addUploadFile($group_id, $fileName, $fileInfo, $fileType, $isdefault)
    {
        // 存储引擎
        $storage = $this->config['default'];
        // 存储域名
        $fileUrl = isset($this->config['engine'][$storage]) ? $this->config['engine'][$storage]['domain'] : '';
        // 添加文件库记录
        $model = new DeliveryImgModel;
        $model->allowField(true)->save([
            'group_id' => $group_id > 0 ? (int)$group_id : 0, //'文件分组id',
            'storage' => $storage, //'存储方式',
            'file_url' => $fileUrl, //'存储域名',
            'file_name' => $fileName, //'文件路径',
            'file_size' => $fileInfo['size'], //'文件大小(字节)',
            'file_type' => $fileType, // '文件类型',
            'extension' => pathinfo($fileInfo['name'], PATHINFO_EXTENSION),
            'is_delete' => 0, // '软删除',
            'wxapp_id' => $this->user['wxapp_id'], //'小程序id',
            'create_time' => time(), //'创建时间',
            'isdefault' => $isdefault, // '是否为默认 Y默认  N非默认',
            'user_id' => $this->user['user_id']
        ]);
        return $model;
    }
    /**
     * 头像上传接口
     * @return array
     * @throws \think\Exception
     */
    public function uploadavatar()
    {
        // 实例化存储驱动
        $StorageDriver = new StorageDriver($this->config);
        // 上传图片
        if (!$StorageDriver->upload())
            return json(['code' => 0, 'msg' => '图片上传失败' . $StorageDriver->getError()]);
        // 图片上传路径
        $fileName = $StorageDriver->getFileName();
        // 图片信息
//        $fileInfo = $StorageDriver->getFileInfo();
//        // 添加文件库记录
//        $uploadFile = $this->addavatar($fileName, $fileInfo);

        // 存储引擎
        $storage = $this->config['default'];
        // 存储域名
        $fileUrl = isset($this->config['engine'][$storage]) ? $this->config['engine'][$storage]['domain'] : '';
        // 添加文件库记录
        $model = new UserModel;
        $model->allowField(true)->save([
            'avatarUrl' => $fileUrl.'/'.$fileName, //'存储域名+文件路径',
            'wxapp_id' => $this->user['wxapp_id'], //'小程序id',
        ],['user_id' => $this->user['user_id']]);
        // 图片上传成功
        return json(['code' => 1, 'msg' => '图片上传成功', 'data' => $model]);
    }

    /**
     * 修改用户信息
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function userupdate()
    {
        $aPost = $this->request->post();
        $model = new UserModel;

        $da = $model->allowField(true)->save($aPost, ['user_id' => $this->user['user_id']]);
        return $this->renderSuccess($da);
    }

    /**
     * 修改用户在线状态
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function isworkingupdate()
    {
        $aPost = $this->request->post();
        $model = new UserModel;
        $update = [];
        $userId = 0;
        if (isset($aPost['isworking']) && !empty($aPost['isworking'])) {
            $update['isworking'] = $aPost['isworking'];
            $userId = $aPost['user_id'];
        }
        if (isset($aPost['isonline']) && !empty($aPost['isonline'])) {
            $update['isonline'] = $aPost['isonline'];
            $userId = $this->user['user_id'];
        }
        if (!$update) {
            return $this->renderError('没有修改参数！');
        }
        $da = $model->allowField(true)->save($update, ['user_id' => $userId]);
        return $this->renderSuccess($da);
    }

    /**
     * 修改用户信息
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function userdelivery()
    {
        return (new MyfavModel)->where(['user_id' => $this->user['user_id']])->count();

        $aPost = $this->request->post();

        $model = new UserModel;
        $update = [
            'nickName' => $aPost['nickName'],
            'avatarUrl' => $aPost['avatarUrl'],
            'gender' => $aPost['gender'],
            'country' => $aPost['country'],
            'province' => $aPost['province'],
            'city' => $aPost['city'],
            'signature' => $aPost['signature'],
            'horoscope' => $aPost['horoscope'],
            'birthday' => $aPost['birthday'],
            'phone' => $aPost['phone'],
            'year' => $aPost['year'],
            'month' => $aPost['month'],
            'day' => $aPost['day'],
        ];
        $da = $model->allowField(true)->save($update, ['user_id' => $this->user['user_id']]);
        return $this->renderSuccess($da);
    }

}
